package info.ask4research.util;

import info.ask4research.model.User;

import java.util.ArrayList;
import java.util.List;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.springframework.stereotype.Component;


/**
 * Util class. Contains some common methods that can be used
 * for any class
 * 
 * @author Loiane Groner
 * http://loianegroner.com (English)
 * http://loiane.com (Portuguese)
 */
@Component
public class Util {
	
	
	/**
	 * Get list of Contacts from request.
	 * @param data - json data from request 
	 * @return list of Contacts
	 */
	public List<User> getUsersFromRequest(Object data){

		List<User> list;

		//it is an array - have to cast to array object
		if (data.toString().indexOf('[') > -1){

			list = getListUserFromJSON(data);

		} else { //it is only one object - cast to object/bean

			User user = getUserFromJSON(data);

			list = new ArrayList<User>();
			list.add(user);
		}

		return list;
	}

	
	/**
	 * Transform json data format into User object
	 * @param data - json data from request
	 * @return 
	 */
	private User getUserFromJSON(Object data){
		JSONObject jsonObject = JSONObject.fromObject(data);
		User newUser = (User) JSONObject.toBean(jsonObject, User.class);
		return newUser;
	}

	
	/**
	 * Transform json data format into list of User objects
	 * @param data - json data from request
	 * @return
	 */
	@SuppressWarnings("unchecked")
	private List<User> getListUserFromJSON(Object data){
		JSONArray jsonArray = JSONArray.fromObject(data);
		List<User> newUsers = (List<User>) JSONArray.toCollection(jsonArray,User.class);
		return newUsers;
	}

	/**
	 * Tranform array of numbers in json data format into
	 * list of Integer
	 * @param data - json data from request
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public List<Integer> getListIdFromJSON(Object data){
		JSONArray jsonArray = JSONArray.fromObject(data);
		List<Integer> ids = (List<Integer>) JSONArray.toCollection(jsonArray,Integer.class);
		return ids;
	}
}
